<template>
  <view class="expansion-container">
    <u-navbar
      title="信息化拓展"
      :border-bottom="false"
      back-icon-color="#007aff"
      back-text="返回"
      :back-text-style="{color: '#007aff'}"
      :custom-style="{background: '#ffffff', boxShadow: '0 2px 10px rgba(0, 0, 0, 0.05)'}"
      :safe-area-inset-top="true"
      :auto-back="true"
      fixed
    ></u-navbar>

    <!-- 导航栏占位，解决fixed定位导致的内容被遮挡问题 -->
    <view class="navbar-placeholder"></view>

    <view class="content-wrapper">
      <view class="group-info-card">
        <view class="card-title">
          <u-icon name="home-fill" size="24" color="#2b85e4"></u-icon>
          <text>{{ groupInfo.name }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">客户编码：</text>
          <text class="info-value">{{ groupInfo.code || '暂无' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">县区：</text>
          <text class="info-value">{{ groupInfo.district || '暂无' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">行业：</text>
          <text class="info-value">{{ groupInfo.industry || '暂无' }}</text>
        </view>
      </view>

      <!-- 异网专线摸排情况卡片 -->
      <view class="other-network-card" @click="showOtherNetworkEditPopup">
        <view class="card-title">
          <u-icon name="wifi" size="24" color="#ff9900"></u-icon>
          <text>异网专线摸排情况</text>
          <u-icon name="edit-pen" size="20" color="#2b85e4"></u-icon>
        </view>
        <view class="info-row">
          <text class="info-label">异网专线资费：</text>
          <text class="info-value">{{ groupInfo.otherNetworkRate || '暂无' }}</text>
          <text class="fee-unit" v-if="groupInfo.otherNetworkRate">元/年</text>
        </view>
        <view class="info-row">
          <text class="info-label">异网专线到期时间：</text>
          <text
            class="info-value"
            :class="{'expire-soon': isExpireSoon, 'expired': isExpired}"
          >{{ groupInfo.otherNetworkExpireDate || '暂无' }}</text>
          <text class="expire-tag" v-if="isExpireSoon">即将到期</text>
          <text class="expire-tag expired" v-if="isExpired">已到期</text>
        </view>
      </view>

      <view class="category-tabs">
        <scroll-view scroll-x class="tabs-scroll" :show-scrollbar="false">
          <view
            class="tab-item"
            v-for="(item, index) in categories"
            :key="index"
            :class="{ active: currentCategory === item.value }"
            @click="switchCategory(item.value)"
          >{{ item.label }}</view>
        </scroll-view>
      </view>

      <view class="expansion-list">
        <view v-if="filteredList.length === 0" class="empty-list">
          <u-empty mode="data" text="暂无拓展记录"></u-empty>
        </view>

        <view v-else class="list-content">
          <view class="expansion-item" v-for="(item, index) in filteredList" :key="index">
            <view class="item-header">
              <view class="product-info">
                <view
                  class="category-tag"
                  :class="getCategoryClass(item.category)"
                >{{ getCategoryName(item.category) }}</view>
                <view class="item-product">{{ item.productName }}</view>
              </view>
              <view class="item-status" :class="getStatusClass(item.status)">{{ item.statusText }}</view>
            </view>
            <view class="item-content">
              <view @click="viewDetail(item.id)">
                <view class="info-grid">
                  <view class="info-grid-item">
                    <text class="info-label">预计数量</text>
                    <text class="info-value">{{ item.quantity }}</text>
                  </view>
                  <view class="info-grid-item right-aligned">
                    <text class="info-label">预计金额</text>
                    <view class="amount-wrapper">
                      <text class="info-value highlight">¥ {{ formatAmount(item.amount) }}</text>
                      <text class="unit">/年</text>
                    </view>
                  </view>
                  <view class="info-grid-item full-width">
                    <view class="expected-date-row">
                      <view>
                        <text class="info-label">预计落地时间</text>
                        <text class="info-value">{{ formatDate(item.expectedTime) }}</text>
                      </view>
                      <!-- <view class="edit-icon" @click="editItem(item.id)"> -->
                      <u-icon name="edit-pen" size="18" color="#2b85e4" @click="editItem(item.id)"></u-icon>
                      <!-- </view> -->
                    </view>
                  </view>
                </view>
              </view>

              <!-- 跟进记录数量和展开按钮 -->
              <view class="progress-count-bar">
                <view @click="toggleRecordsView(item)">
                  <view class="progress-count-info">
                    <u-icon name="file-text-fill" size="14" color="#2b85e4"></u-icon>
                    <text
                      class="progress-count-text"
                    >{{ item.progressRecords && item.progressRecords.length ? item.progressRecords.length : 0 }}条跟进记录</text>
                  </view>
                  <view class="progress-bar-actions">
                    <u-icon
                      v-if="item.progressRecords && item.progressRecords.length > 0"
                      :name="expandedItems[item.id] ? 'arrow-up' : 'arrow-down'"
                      size="14"
                      color="#95a5a6"
                      class="arrow-icon"
                    ></u-icon>
                  </view>
                </view>

                <u-button
                  v-if="item.status === '跟进中'"
                  type="primary"
                  size="mini"
                  class="progress-btn"
                  @click="onAddProgress(item.id)"
                >+</u-button>
              </view>

              <!-- 展开的跟进记录列表 -->
              <view
                class="progress-timeline"
                v-if="expandedItems[item.id] && item.progressRecords && item.progressRecords.length > 0"
              >
                <view
                  class="timeline-item"
                  v-for="(record, recordIndex) in item.progressRecords"
                  :key="recordIndex"
                >
                  <view class="timeline-left">
                    <view class="timeline-dot"></view>
                    <view
                      class="timeline-line"
                      v-if="recordIndex !== item.progressRecords.length - 1"
                    ></view>
                  </view>
                  <view class="timeline-right">
                    <view class="timeline-header">
                      <text class="timeline-date">{{ formatProgressTime(record.createTime) }}</text>
                      <text class="timeline-time">{{ getProgressTimeOnly(record.createTime) }}</text>
                    </view>
                    <view class="timeline-content">{{ record.content }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 悬浮按钮 -->
    <view class="float-btn" @click="addExpansion">
      <u-icon name="plus" color="#ffffff" size="28"></u-icon>
      <view class="float-btn-ripple"></view>
    </view>

    <!-- 异网专线编辑弹窗 -->
    <view
      class="custom-popup-mask"
      v-if="showOtherNetworkPopup"
      @click.stop="onOtherNetworkMaskClick"
    >
      <view class="custom-popup-content" @click.stop>
        <view class="custom-popup-close" @click="closeOtherNetworkPopup">×</view>
        <view class="popup-content">
          <view class="popup-title">编辑异网专线信息</view>

          <view class="form-content">
            <view class="popup-product-info">
              <view class="popup-product-name">{{ groupInfo.name || '未知集团' }}</view>
            </view>

            <view class="form-group">
              <view class="form-row">
                <view class="form-label date-label">异网专线资费</view>
                <view class="form-control">
                  <u-input
                    v-model="otherNetworkForm.fee"
                    type="number"
                    placeholder="请输入异网专线资费"
                    :border="true"
                    :clearable="true"
                    class="custom-input"
                  ></u-input>
                  <text class="input-unit">元/年</text>
                </view>
              </view>
            </view>

            <view class="form-group">
              <view class="form-row">
                <view class="form-label date-label">异网专线到期时间</view>
                <view class="form-control date-picker">
                  <picker
                    mode="date"
                    :value="otherNetworkForm.expireDate"
                    @change="otherNetworkDateChange"
                  >
                    <view class="picker-value">
                      <text>{{ otherNetworkForm.expireDate || '请选择到期日期' }}</text>
                      <u-icon name="calendar" size="16" color="#c0c4cc"></u-icon>
                    </view>
                  </picker>
                </view>
              </view>
            </view>
          </view>

          <view class="popup-footer">
            <u-button type="default" shape="circle" @click="closeOtherNetworkPopup" :plain="true">取消</u-button>
            <u-button
              type="primary"
              shape="circle"
              @click="saveOtherNetworkInfo"
              :loading="otherNetworkLoading"
            >保存</u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 跟进记录弹窗 -->
    <view class="custom-popup-mask" v-if="showPopup" @click.stop="onMaskClick">
      <view class="custom-popup-content" @click.stop>
        <view class="custom-popup-close" @click="closePopup">×</view>
        <view class="popup-content">
          <view class="popup-title">新增跟进记录</view>

          <view class="form-content">
            <view class="popup-product-info" v-if="currentExpansion">
              <view class="popup-product-name">{{ currentExpansion.productName }}</view>
              <view
                class="popup-product-status"
                :class="getStatusClass(currentExpansion.status)"
              >{{ currentExpansion.statusText }}</view>
            </view>

            <view class="form-group">
              <view class="form-label">跟进日期</view>
              <view class="form-control date-picker">
                <picker
                  mode="date"
                  :value="followDate"
                  :end="getCurrentDate(true)"
                  @change="dateChange"
                >
                  <view class="picker-value">
                    <text>{{ followDate || '请选择日期' }}</text>
                    <u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
                  </view>
                </picker>
              </view>
            </view>

            <view class="form-group">
              <view class="form-label">目前跟进情况</view>
              <view class="form-control">
                <u-textarea
                  v-model="progressContent"
                  placeholder="支持按日期记录更新内容，例：拜访客户单位***，沟通了**产品的报价及设计方案，**意向8月份建设，对我公司该项产品的意见为......"
                  height="100"
                  count
                  maxlength="300"
                ></u-textarea>
              </view>
            </view>
          </view>

          <view class="popup-footer">
            <u-button type="default" shape="circle" @click="closePopup" :plain="true">取消</u-button>
            <u-button type="primary" shape="circle" @click="saveProgress" :loading="loading">保存</u-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupCode: "",
      groupInfo: {
        name: "",
        code: "",
        district: "",
        industry: "",
        industryCode: "",
        industryChain: "",
        manager: "",
        otherNetworkRate: "",
        otherNetworkExpireDate: ""
      },
      otherNetworkForm: {
        fee: "",
        expireDate: ""
      },
      showOtherNetworkPopup: false,
      otherNetworkLoading: false,
      currentCategory: "all",
      currentExpansionId: "",
      currentExpansion: null,
      showPopup: false,
      progressContent: "",
      expandedItems: {}, // 用于跟踪展开状态的对象
      categories: [
        { label: "全部", value: "all" },
        { label: "专线", value: "专线" },
        { label: "移动云", value: "移动云" },
        { label: "物联网", value: "物联网" },
        { label: "短彩信", value: "短彩信" },
        { label: "其他", value: "其他" }
      ],
      expansionList: [],
      followDate: "",
      loading: false, // 添加loading状态
      useLocalFilter: false // 添加useLocalFilter属性
    };
  },
  computed: {
    filteredList() {
      if (this.currentCategory === "all") {
        return this.expansionList;
      } else {
        return this.expansionList.filter(
          item => item.category === this.currentCategory
        );
      }
    },
    // 判断是否即将到期（3个月内）
    isExpireSoon() {
      if (!this.groupInfo.otherNetworkExpireDate) return false;

      const expireDate = new Date(this.groupInfo.otherNetworkExpireDate);
      const today = new Date();

      // 设置今天的时间为00:00:00，便于比较
      today.setHours(0, 0, 0, 0);

      // 计算3个月后的日期
      const threeMonthsLater = new Date(today);
      threeMonthsLater.setMonth(today.getMonth() + 3);

      // 如果到期日期在今天之后且在3个月内，则视为即将到期
      return expireDate > today && expireDate <= threeMonthsLater;
    },

    // 判断是否已到期
    isExpired() {
      if (!this.groupInfo.otherNetworkExpireDate) return false;

      const expireDate = new Date(this.groupInfo.otherNetworkExpireDate);
      const today = new Date();

      // 设置今天的时间为00:00:00，便于比较
      today.setHours(0, 0, 0, 0);

      // 如果到期日期在今天或之前，则视为已到期
      return expireDate <= today;
    }
  },
  onLoad(options) {
    // 确保初始状态正确
    this.showPopup = false;
    this.currentExpansion = null;
    this.currentExpansionId = "";

    // 打印接收到的参数，帮助调试
    console.log("拓展页面接收到的参数:", options);

    // 获取groupCode参数
    if (options && options.groupCode) {
      console.log("获取到有效的groupCode:", options.groupCode);
      this.groupCode = options.groupCode; // 使用groupCode作为变量名
      this.getGroupInfo();
      this.getExpansionList();
    } else {
      console.log("未获取到有效的groupCode，options:", JSON.stringify(options));
      uni.showToast({
        title: "缺少集团单位编码",
        icon: "none"
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  onShow() {
    // 从其他页面返回时刷新列表
    if (this.groupCode) {
      this.getExpansionList();
    }
  },
  methods: {
    // 获取集团单位信息
    getGroupInfo() {
      console.log("开始获取集团信息，groupCode:", this.groupCode);

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 调用接口获取集团信息
      this.$http
        .sendRequest("zhanke/group_detail", "POST", {
          groupCode: this.groupCode
        })
        .then(res => {
          uni.hideLoading();
          console.log("集团信息API返回:", res.data);

          if (res.data && res.data.code === 200) {
            // 设置集团信息
            const detail = res.data.data;
            this.groupInfo = {
              name: detail.name,
              code: detail.code,
              district: detail.district,
              industry: detail.industry,
              industryCode: detail.industryCode,
              industryChain: detail.industryChain,
              manager: detail.manager,
              otherNetworkRate: detail.otherNetworkRate,
              otherNetworkExpireDate: detail.otherNetworkExpireDate
            };
            console.log("集团信息获取成功:", this.groupInfo);
          } else {
            // 请求失败处理
            console.error("获取集团信息失败:", res.data.msg);
            uni.showToast({
              title: res.data.msg || "获取集团信息失败",
              icon: "none"
            });
            // 获取不到数据时使用本地默认数据
            this.getGroupInfoFromStorage();
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取集团信息出错:", err);
          // 请求出错，使用本地数据
          this.getGroupInfoFromStorage();
          uni.showToast({
            title: "网络请求失败，显示本地数据",
            icon: "none"
          });
        });
    },

    // 从本地存储获取集团信息
    getGroupInfoFromStorage() {
      try {
        const storageData = uni.getStorageSync("groupInfo_" + this.groupCode);
        if (storageData) {
          this.groupInfo = JSON.parse(storageData);
        } else {
          // 本地无数据时使用默认数据
          this.groupInfo = {
            name: "未知集团单位",
            code: this.groupCode,
            district: "未知",
            industry: "未知",
            industryCode: "",
            industryChain: "",
            manager: "",
            otherNetworkRate: "",
            otherNetworkExpireDate: ""
          };
        }
      } catch (e) {
        console.error("读取本地存储出错:", e);
        this.groupInfo = {
          name: "未知集团单位",
          code: this.groupCode,
          district: "未知",
          industry: "未知",
          otherNetworkRate: "",
          otherNetworkExpireDate: ""
        };
      }
    },

    // 显示异网专线编辑弹窗
    showOtherNetworkEditPopup() {
      // 复制当前值到表单
      this.otherNetworkForm.fee = this.groupInfo.otherNetworkRate
        ? String(this.groupInfo.otherNetworkRate)
        : "";
      this.otherNetworkForm.expireDate =
        this.groupInfo.otherNetworkExpireDate || "";
      this.showOtherNetworkPopup = true;
    },

    // 关闭异网专线编辑弹窗
    closeOtherNetworkPopup() {
      this.showOtherNetworkPopup = false;
    },

    // 点击异网专线弹窗遮罩层
    onOtherNetworkMaskClick() {
      this.closeOtherNetworkPopup();
    },

    // 异网专线日期选择变更
    otherNetworkDateChange(e) {
      this.otherNetworkForm.expireDate = e.detail.value;
    },

    // 保存异网专线信息
    saveOtherNetworkInfo() {
      // 验证表单
      if (
        this.otherNetworkForm.fee &&
        isNaN(Number(this.otherNetworkForm.fee))
      ) {
        uni.showToast({
          title: "请输入有效的资费金额",
          icon: "none"
        });
        return;
      }

      // 防止重复提交
      if (this.otherNetworkLoading) return;
      this.otherNetworkLoading = true;

      // 显示加载提示
      uni.showLoading({
        title: "保存中..."
      });

      // 调用接口保存信息
      this.$http
        .sendRequest("zhanke/update_group_other_network", "POST", {
          groupCode: this.groupCode,
          otherNetworkRate: this.otherNetworkForm.fee
            ? Number(this.otherNetworkForm.fee)
            : null,
          otherNetworkExpireDate: this.otherNetworkForm.expireDate || null
        })
        .then(res => {
          uni.hideLoading();
          this.otherNetworkLoading = false;

          if (res.data && res.data.code === 200) {
            // 保存成功
            uni.showToast({
              title: "保存成功",
              icon: "success"
            });

            // 更新本地数据
            this.groupInfo.otherNetworkRate = this.otherNetworkForm.fee
              ? Number(this.otherNetworkForm.fee)
              : "";
            this.groupInfo.otherNetworkExpireDate =
              this.otherNetworkForm.expireDate || "";

            // 保存到本地存储
            try {
              uni.setStorageSync(
                "groupInfo_" + this.groupCode,
                JSON.stringify(this.groupInfo)
              );
            } catch (e) {
              console.error("保存集团信息出错:", e);
            }

            // 关闭弹窗
            this.closeOtherNetworkPopup();

            // 刷新页面数据
            this.getExpansionList();
          } else {
            // 保存失败
            uni.showToast({
              title: res.data.msg || "保存失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          this.otherNetworkLoading = false;

          // 接口请求失败
          uni.showToast({
            title: "网络请求失败",
            icon: "none"
          });
        });
    },

    // 获取信息化拓展列表
    getExpansionList() {
      console.log(
        "开始获取拓展列表，groupCode:",
        this.groupCode,
        "类别:",
        this.currentCategory
      );

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 调用接口获取拓展列表
      this.$http
        .sendRequest("zhanke/expansion_list", "POST", {
          groupCode: this.groupCode,
          category: this.currentCategory !== "all" ? this.currentCategory : "", // 仅在选择了具体类别时传入
          page: 1,
          limit: 50
        })
        .then(res => {
          uni.hideLoading();
          console.log("拓展列表API返回:", res.data);

          if (res.data && res.data.code === 200) {
            const list = res.data.data.list || [];
            console.log("获取到拓展列表数量:", list.length);

            // 将API返回的数据格式化为组件需要的格式
            this.expansionList = list.map(item => {
              // 状态文本对应
              const statusMap = {
                跟进中: "跟进中",
                已落地: "已落地",
                已废弃: "已废弃"
              };

              // 设置状态
              const status = statusMap[item.status] || "跟进中";

              return {
                id: item.id,
                groupCode: item.groupCode,
                category: item.category || "其他",
                productName: item.productName,
                quantity: item.quantity || 0,
                amount: item.estimatedAmount || 0,
                expectedTime: item.expectedLandingDate,
                manager: item.manager,
                status: status,
                statusText: status,
                isProject: item.isProject || false,
                isLanded: item.isLanded || false,
                progressRecords: item.progressRecords || []
              };
            });

            // 保存到本地缓存
            this.saveExpansionList();
          } else {
            // API请求失败，尝试从本地存储获取
            console.error("获取拓展列表失败:", res.data.msg);
            this.getExpansionListFromStorage();

            uni.showToast({
              title: res.data.msg || "获取拓展记录失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取拓展列表出错:", err);
          // API请求错误，尝试从本地存储获取
          this.getExpansionListFromStorage();

          uni.showToast({
            title: "网络请求失败，显示本地数据",
            icon: "none"
          });
        });
    },

    // 从本地存储获取拓展列表
    getExpansionListFromStorage() {
      try {
        const storageData = uni.getStorageSync(
          "expansionList_" + this.groupCode
        );
        if (storageData) {
          this.expansionList = JSON.parse(storageData);
        } else {
          // 本地无数据时使用空数组
          this.expansionList = [];
        }
      } catch (e) {
        console.error("读取本地存储出错:", e);
        this.expansionList = [];
      }
    },

    // 保存拓展列表到本地存储
    saveExpansionList() {
      try {
        uni.setStorageSync(
          "expansionList_" + this.groupCode,
          JSON.stringify(this.expansionList)
        );
      } catch (e) {
        console.error("保存本地存储出错:", e);
      }
    },

    // 切换展开/收起跟进记录
    toggleRecordsView(item) {
      // 如果已经展开，则收起
      if (this.expandedItems[item.id]) {
        this.$set(this.expandedItems, item.id, false);
        return;
      }

      // 如果要展开且有跟进记录，则尝试加载最新的跟进记录
      if (item.progressRecords && item.progressRecords.length > 0) {
        // 显示加载提示
        uni.showLoading({
          title: "加载记录..."
        });

        // 调用接口获取跟进记录
        this.$http
          .sendRequest("zhanke/expansion_follow_list", "POST", {
            expansionId: item.id,
            page: 1,
            limit: 20
          })
          .then(res => {
            uni.hideLoading();

            if (res.data && res.data.code === 200) {
              const records = res.data.data.list || [];

              // 更新跟进记录
              if (records.length > 0) {
                // 格式化API返回的跟进记录
                const formattedRecords = records.map(record => {
                  return {
                    id: record.id,
                    createTime: record.createTime,
                    content: record.followContent
                  };
                });

                // 更新记录
                item.progressRecords = formattedRecords;

                // 保存到本地缓存
                this.saveExpansionList();
              }
            }

            // 切换状态（无论请求成功与否都展开，仅展示本地数据）
            this.$set(this.expandedItems, item.id, true);
          })
          .catch(err => {
            console.error("获取跟进记录出错:", err);
            uni.hideLoading();

            // 发生错误时仍然展开，显示本地数据
            this.$set(this.expandedItems, item.id, true);

            uni.showToast({
              title: "加载记录失败，显示本地数据",
              icon: "none"
            });
          });
      } else {
        // 无记录或其他情况，直接切换状态
        this.$set(this.expandedItems, item.id, true);
      }
    },

    // 格式化金额
    formatAmount(amount) {
      return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "暂无";
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}/${month}/${day}`;
    },

    // 格式化跟进记录时间（只返回日期部分）
    formatProgressTime(timeString) {
      if (!timeString) return "";

      try {
        const date = new Date(timeString);
        if (isNaN(date.getTime())) {
          // 尝试简单格式化，如果是字符串形式
          return timeString.split(" ")[0];
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error("日期格式化错误:", e);
        // 失败则尝试简单分割
        return timeString.split(" ")[0];
      }
    },

    // 获取时间部分
    getProgressTimeOnly(timeString) {
      if (!timeString) return "";

      try {
        const date = new Date(timeString);
        if (isNaN(date.getTime())) {
          // 尝试简单格式化，如果是字符串形式
          const parts = timeString.split(" ");
          return parts.length > 1 ? parts[1] : "";
        }

        const hour = String(date.getHours()).padStart(2, "0");
        const minute = String(date.getMinutes()).padStart(2, "0");
        return `${hour}:${minute}`;
      } catch (e) {
        console.error("时间格式化错误:", e);
        // 失败则尝试简单分割
        const parts = timeString.split(" ");
        return parts.length > 1 ? parts[1] : "";
      }
    },

    // 截断文本
    truncateText(text, maxLength) {
      if (!text) return "";
      if (text.length <= maxLength) return text;
      return text.substring(0, maxLength) + "...";
    },

    // 切换产品类别
    switchCategory(category) {
      // 切换当前类别
      this.currentCategory = category;

      // 如果使用本地过滤，无需重新请求
      if (this.useLocalFilter) {
        return;
      }

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 调用接口获取拓展列表
      this.$http
        .sendRequest("zhanke/expansion_list", "POST", {
          groupCode: this.groupCode,
          category: category !== "all" ? category : "", // 仅在选择了具体类别时传入
          page: 1,
          limit: 50
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            const list = res.data.data.list || [];

            // 将API返回的数据格式化为组件需要的格式
            this.expansionList = list.map(item => {
              // 状态文本对应
              const statusMap = {
                跟进中: "跟进中",
                已落地: "已落地",
                已废弃: "已废弃"
              };

              // 设置状态
              const status = statusMap[item.status] || "跟进中";

              return {
                id: item.id,
                groupCode: item.groupCode,
                category: item.category || "其他",
                productName: item.productName,
                quantity: item.quantity || 0,
                amount: item.estimatedAmount || 0,
                expectedTime: item.expectedLandingDate,
                manager: item.manager,
                status: status,
                statusText: status,
                isProject: item.isProject || false,
                isLanded: item.isLanded || false,
                progressRecords: item.progressRecords || []
              };
            });

            // 保存到本地缓存
            this.saveExpansionList();
          } else {
            // 请求失败时不改变当前数据
            uni.showToast({
              title: res.data.msg || "获取分类数据失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取分类数据出错:", err);

          uni.showToast({
            title: "网络请求失败",
            icon: "none"
          });
        });
    },

    // 获取状态对应的样式类
    getStatusClass(status) {
      switch (status) {
        case "跟进中":
          return "status-progress";
        case "已落地":
          return "status-completed";
        case "已废弃":
          return "status-abandoned";
        default:
          return "";
      }
    },

    // 查看详情
    viewDetail(id) {
      uni.navigateTo({
        url: `/pages/business/expansion/detail?groupCode=${this.groupCode}&expansionId=${id}`
      });
    },

    // 编辑拓展项
    editItem(id) {
      uni.navigateTo({
        url: `/pages/business/expansion/edit?groupCode=${this.groupCode}&expansionId=${id}`
      });
    },

    // 关闭弹窗
    closePopup() {
      this.showPopup = false;

      // 延迟清理数据，避免闪烁
      setTimeout(() => {
        this.currentExpansion = null;
        this.currentExpansionId = "";
        this.progressContent = "";
        this.followDate = "";
      }, 300);
    },

    // 点击遮罩层关闭弹窗
    onMaskClick() {
      this.closePopup();
    },

    // 新增跟进记录
    onAddProgress(id) {
      // 找到对应项
      const item = this.expansionList.find(item => item.id === id);
      if (!item) {
        console.log("未找到对应项:", id);
        return;
      }

      console.log("准备添加跟进记录:", item.productName);

      // 先重置状态
      this.showPopup = false;
      this.currentExpansion = null;
      this.currentExpansionId = "";
      this.progressContent = "";
      this.followDate = "";

      // 必须使用setTimeout，确保先完成状态重置
      setTimeout(() => {
        // 重新设置数据
        this.currentExpansion = item;
        this.currentExpansionId = id;
        this.progressContent = "";
        // 设置今天的日期，格式为YYYY-MM-DD
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, "0");
        const day = String(today.getDate()).padStart(2, "0");
        this.followDate = `${year}-${month}-${day}`;

        // 使用进一步的延迟打开弹窗
        setTimeout(() => {
          this.showPopup = true;
          console.log(
            "打开弹窗:",
            this.showPopup,
            "产品:",
            this.currentExpansion.productName
          );
        }, 100);
      }, 100);
    },

    // 用于调试弹窗问题
    debugPopup() {
      console.log("Current popup state:", {
        showPopup: this.showPopup,
        currentExpansion: this.currentExpansion
          ? this.currentExpansion.id
          : null
      });

      // 尝试打开弹窗
      this.showPopup = true;
    },

    // 打开日期选择器
    openDatePicker() {
      // 使用原生组件选择器，不需要关闭弹窗
      const picker = this.$refs.datePicker;
      if (picker) {
        picker.show();
      } else {
        // 如果无法获取到picker引用，则使用普通输入
        uni.showToast({
          title: "请直接输入日期",
          icon: "none"
        });
      }
    },

    // 日期选择改变
    dateChange(e) {
      this.followDate = e.detail.value;
    },

    getCurrentDate(onlyDate) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      if (onlyDate) {
        return `${year}-${month}-${day}`;
      } else {
        const hour = String(now.getHours()).padStart(2, "0");
        const minute = String(now.getMinutes()).padStart(2, "0");
        const second = String(now.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      }
    },

    // 新增产品大类和子产品的显示
    getCategoryClass(category) {
      // 根据产品类别返回相应的样式类
      switch (category) {
        case "专线":
          return "category-line";
        case "移动云":
          return "category-cloud";
        case "物联网":
          return "category-iot";
        case "短彩信":
          return "category-sms";
        case "其他":
          return "category-other";
        default:
          return "category-other";
      }
    },

    getCategoryName(category) {
      // 直接返回分类名称，不再进行映射转换
      return category || "其他";
    },

    // 保存跟进记录
    saveProgress() {
      // 验证输入
      if (!this.progressContent.trim()) {
        uni.showToast({
          title: "请输入跟进情况",
          icon: "none"
        });
        return;
      }

      if (!this.followDate) {
        uni.showToast({
          title: "请选择跟进日期",
          icon: "none"
        });
        return;
      }

      // 设置加载状态
      this.loading = true;

      // 显示加载
      uni.showLoading({
        title: "保存中...",
        mask: true
      });

      // 格式化日期为中文显示，如：8月7日
      const dateParts = this.followDate.split("-");
      const month = parseInt(dateParts[1]);
      const day = parseInt(dateParts[2]);
      const chineseDate = `${month}月${day}日`;

      // 组合内容，自动添加日期前缀
      const fullContent = `${chineseDate}，${this.progressContent}`;

      // 调用接口保存跟进记录
      this.$http
        .sendRequest("zhanke/expansion_follow_add", "POST", {
          expansionId: this.currentExpansionId,
          followDate: this.followDate,
          followContent: fullContent
        })
        .then(res => {
          if (res.data && res.data.code === 200) {
            // 获取新记录ID
            const newRecordId = res.data.data.id;

            // 添加当前时间
            const now = new Date();
            const hours = String(now.getHours()).padStart(2, "0");
            const minutes = String(now.getMinutes()).padStart(2, "0");

            // 组合日期和时间
            const createTime = `${this.followDate} ${hours}:${minutes}`;

            // 在本地数据中添加新记录
            const expansion = this.expansionList.find(
              item => item.id === this.currentExpansionId
            );

            if (expansion) {
              // 创建新记录对象
              const newRecord = {
                id: newRecordId,
                createTime,
                content: fullContent
              };

              // 将新记录添加到数组开头
              if (!expansion.progressRecords) {
                expansion.progressRecords = [];
              }
              expansion.progressRecords.unshift(newRecord);

              // 自动展开此项的跟进记录
              this.$set(this.expandedItems, this.currentExpansionId, true);

              // 保存到本地存储
              this.saveExpansionList();
            }

            uni.hideLoading();
            this.loading = false;
            uni.showToast({
              title: "新增成功",
              icon: "success"
            });

            this.closePopup();
          } else {
            uni.hideLoading();
            this.loading = false;
            uni.showToast({
              title: res.data.msg || "保存失败，请重试",
              icon: "none"
            });
          }
        })
        .catch(err => {
          console.error("保存跟进记录出错:", err);
          uni.hideLoading();
          this.loading = false;
          uni.showToast({
            title: "网络请求失败，请重试",
            icon: "none"
          });
        });
    },

    // 新增信息化拓展
    addExpansion() {
      uni.navigateTo({
        url: `/pages/business/expansion/edit?groupCode=${this.groupCode}`
      });
    },

    formatDisplayDateTime(dateTime) {
      if (!dateTime) return "";
      return dateTime; // 简化为直接返回日期字符串
    },

    formatChineseDate(date) {
      if (!date) return "";
      const dateObj = new Date(date);
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, "0");
      const day = String(dateObj.getDate()).padStart(2, "0");
      return `${year}年${month}月${day}日`;
    }
  }
};
</script>

<style>
.expansion-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 30px;
  position: relative;
}

/* 导航栏占位，防止内容被固定导航栏遮挡 */
.navbar-placeholder {
  height: 88rpx;
  /* 如果有状态栏，可能需要增加高度 */
  padding-top: var(--status-bar-height);
}

.content-wrapper {
  padding: 10px 12px 20px;
}

.group-info-card {
  background: linear-gradient(135deg, #ffffff, #f8fbff);
  border-radius: 16px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 6px 20px rgba(43, 133, 228, 0.08);
  border: 1px solid #e6e6e6;
  transform: translateZ(0);
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e6e6e6;
}

.card-title text {
  margin-left: 10px;
}

.info-row {
  display: flex;
  margin-bottom: 6px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 150px;
  color: #7f8c8d;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #34495e;
  font-size: 14px;
  font-weight: 500;
}

.category-tabs {
  margin-bottom: 15px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  border: 1px solid #e6e6e6;
}

.tabs-scroll {
  white-space: nowrap;
  padding: 0 5px;
}

.tab-item {
  display: inline-block;
  padding: 10px 10px;
  font-size: 14px;
  color: #7f8c8d;
  position: relative;
  transition: all 0.3s;
}

.tab-item.active {
  color: #2b85e4;
  font-weight: 600;
  background-color: rgba(43, 133, 228, 0.05);
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 24px;
  height: 3px;
  background-color: #2b85e4;
  border-radius: 3px;
}

.expansion-item {
  background: #ffffff;
  border-radius: 16px;
  padding: 15px;
  margin-bottom: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
  border: 1px solid #e6e6e6;
  transform: translateZ(0);
  transition: all 0.3s;
}

.expansion-item:active {
  transform: translateZ(0) scale(0.98);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e6e6e6;
}

.product-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.category-tag {
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 12px;
  color: #fff;
  margin-right: 8px;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.item-product {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.item-status {
  font-size: 12px;
  padding: 5px 14px;
  border-radius: 20px;
  color: #fff;
  font-weight: 500;
}

.status-progress {
  background: linear-gradient(90deg, #2b85e4, #36a3f7);
  box-shadow: 0 4px 8px rgba(43, 133, 228, 0.3);
}

.status-completed {
  background: linear-gradient(90deg, #19be6b, #1fd078);
  box-shadow: 0 4px 8px rgba(25, 190, 107, 0.3);
}

.status-abandoned {
  background: linear-gradient(90deg, #909399, #a0a3a9);
  box-shadow: 0 4px 8px rgba(144, 147, 153, 0.3);
}

.item-content {
  padding: 5px 0 15px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 5px;
  padding: 8px;
  margin-bottom: 8px;
  background: #f9fafc;
  border-radius: 12px;
  border: 1px solid #e6effc;
}

.info-grid-item {
  flex: 1;
  min-width: 50%;
  margin-bottom: 8px;
  position: relative;
}

.info-grid-item.full-width {
  grid-column: span 2;
}

.info-grid-item .info-label {
  width: auto;
  color: #95a5a6;
  font-size: 12px;
  display: block;
  margin-bottom: 2px;
}

.info-grid-item .info-value {
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
  display: inline-block;
  margin-right: 4px;
}

.info-value.highlight {
  color: #e74c3c;
  font-size: 14px;
  font-weight: 600;
}

.unit {
  font-size: 12px;
  color: #95a5a6;
  margin-left: 2px;
}

/* 跟进记录数量条 */
.progress-count-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 10px;
  margin-top: 10px;
  border: 1px solid #e6e6e6;
  transition: all 0.2s;
}

.progress-count-bar > view:first-child {
  flex: 1;
  display: flex;
  cursor: pointer;
}

.progress-count-bar > view:first-child:active {
  opacity: 0.8;
}

.progress-count-info {
  display: flex;
  align-items: center;
}

.progress-count-text {
  font-size: 12px;
  color: #2c3e50;
  margin-left: 6px;
  font-weight: 500;
}

.progress-bar-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-btn {
  margin: 0 !important;
  padding: 0 !important;
  width: 28px !important;
  height: 28px !important;
  min-width: 28px !important;
  border-radius: 50% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  font-size: 18px !important;
  font-weight: 400 !important;
  line-height: 1 !important;
  box-shadow: 0 2px 6px rgba(43, 133, 228, 0.3) !important;
}

.arrow-icon {
  padding: 4px;
  opacity: 0.8;
}

/* 跟进记录列表 */
.progress-timeline {
  margin-top: 10px;
  border-radius: 8px;
  padding: 3px 0 3px 8px;
  border-left: none;
}

.timeline-item {
  display: flex;
  position: relative;
  padding: 8px 0;
  border-bottom: 1px solid #e6e6e6;
}

.timeline-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.timeline-left {
  position: relative;
  width: 20px;
  height: 100%;
  flex-shrink: 0;
}

.timeline-dot {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2b85e4, #36a3f7);
  position: absolute;
  top: 6px;
  left: 4px;
  box-shadow: 0 0 0 4px #e6effc;
}

.timeline-line {
  width: 2px;
  position: absolute;
  top: 18px;
  bottom: -12px;
  left: 9px;
  background-color: #bedcff;
}

.timeline-right {
  flex: 1;
  padding-left: 15px;
}

.timeline-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.timeline-date {
  font-size: 12px;
  color: #2c3e50;
  font-weight: 600;
  margin-right: 8px;
}

.timeline-time {
  font-size: 12px;
  color: #95a5a6;
}

.timeline-content {
  font-size: 12px;
  color: #34495e;
  line-height: 1.5;
  background-color: #f8f9fa;
  padding: 10px 12px;
  border-radius: 10px;
  position: relative;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  border: 1px solid #e6effc;
}

.timeline-content::before {
  content: "";
  position: absolute;
  left: -8px;
  top: 12px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid #f8f9fa;
}

.expected-date-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.expected-date-row > view:first-child {
  flex: 1;
}

.edit-icon {
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: #e6effc;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-icon:active {
  background-color: #d0e3f9;
  transform: scale(0.95);
}

/* 悬浮按钮样式 */
.float-btn {
  position: fixed;
  right: 25rpx;
  bottom: 50rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #2b85e4, #3498db);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 6px 16px rgba(43, 133, 228, 0.4);
  transition: all 0.3s;
  overflow: hidden;
}

.float-btn:active {
  transform: scale(0.92);
  box-shadow: 0 3px 10px rgba(43, 133, 228, 0.3);
}

.float-btn-ripple {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: #ffffff;
  transform: scale(0);
  animation: ripple 1.5s infinite;
}

@keyframes ripple {
  0% {
    transform: scale(0.5);
    opacity: 0.2;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

/* 自定义弹窗样式，解决层级问题 */
.custom-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 900;
}

.custom-popup-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 16px;
  width: 90%;
  max-width: 400px;
  position: relative;
  z-index: 901;
}

.custom-popup-close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 20px;
  color: #909399;
  cursor: pointer;
}

.popup-content {
  padding: 5px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 25px;
  text-align: center;
}

.form-content {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-label {
  flex: 0 0 130px;
  margin-bottom: 0;
  font-size: 14px;
  color: #606266;
}

.form-control {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

.form-control u-input {
  flex: 1;
}

.custom-input {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 0 8px;
}

.date-picker {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px 12px;
  background-color: #f8f9fa;
}

.picker-value {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
  height: 24px;
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  gap: 15px;
}

.popup-footer u-button {
  flex: 1;
}

/* 保留原有的一些样式 */
.popup-product-info {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #e6e6e6;
}

.popup-product-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
}

.popup-product-status {
  font-size: 12px;
  padding: 5px 14px;
  border-radius: 20px;
  color: #fff;
  font-weight: 500;
}

/* 删除不再需要的旧弹窗样式 */
.custom-modal,
.custom-dialog {
  display: none;
}

.empty-list {
  background-color: #fff;
  border-radius: 16px;
  padding: 40px 0;
  box-shadow: 0 4px 18px rgba(0, 0, 0, 0.05);
  border: 1px solid #e6e6e6;
}

.amount-wrapper {
  display: flex;
  align-items: baseline;
}

.right-aligned {
  text-align: right;
}

.right-aligned .info-label {
  text-align: right;
}

.right-aligned .amount-wrapper {
  justify-content: flex-end;
}

.category-line {
  background: linear-gradient(135deg, #2b85e4, #1a62b3);
}

.category-cloud {
  background: linear-gradient(135deg, #0acffe, #495aff);
}

.category-iot {
  background: linear-gradient(135deg, #13c2c2, #089d9d);
}

.category-sms {
  background: linear-gradient(135deg, #fa8c16, #dc6b12);
}

.category-other {
  background: linear-gradient(135deg, #a0a0a0, #7e7e7e);
}

/* 给所有系统弹出层元素一个更高层级 */
uni-picker-view,
.uni-picker-view-wrapper,
.uni-picker-view-column,
.uni-picker,
.uni-picker-container,


/* 日期选择器修复 */
.date-picker-fix {
  width: 100%;
}
.date-picker-fix .picker {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.other-network-card {
  background: linear-gradient(135deg, #ffffff, #fff8f0);
  border-radius: 16px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 6px 20px rgba(255, 153, 0, 0.08);
  border: 1px solid #ffebb7;
  transform: translateZ(0);
}

.other-network-card .card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ffebb7;
}

.other-network-card .card-title text {
  margin-left: 10px;
  flex: 1;
}

.edit-button {
  display: flex;
  align-items: center;
  padding: 4px 10px;
  background-color: rgba(43, 133, 228, 0.1);
  border-radius: 12px;
  cursor: pointer;
}

.edit-button text {
  font-size: 12px;
  color: #2b85e4;
  margin-left: 4px;
  font-weight: normal;
}

.fee-unit {
  font-size: 12px;
  color: #7f8c8d;
  margin-left: 4px;
}

.expire-tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  background-color: #ff990030;
  color: #ff9900;
  margin-left: 8px;
}

.expire-tag.expired {
  background-color: #ff4d4f30;
  color: #ff4d4f;
}

.expire-soon {
  color: #ff9900;
  font-weight: 500;
}

.expired {
  color: #ff4d4f;
  font-weight: 500;
}

.input-unit {
  margin-left: 10px;
  color: #7f8c8d;
  font-size: 14px;
  white-space: nowrap;
}

.input-tips {
  font-size: 12px;
  color: #95a5a6;
  margin-top: 5px;
  display: block;
}

.form-row {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 12px;
}

.date-label {
  flex: 0 0 130px;
  margin-bottom: 0;
  font-size: 14px;
  color: #606266;
}

.date-picker {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px 12px;
  background-color: #f8f9fa;
}

.form-control {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

.form-control u-input {
  flex: 1;
}
</style> 